package com.dzf.dao;

import com.dzf.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Repository;

@Repository
public class UserDao {
    @Autowired
    MongoTemplate mongoTemplate;



    public User findById(String id) {
        return mongoTemplate.findById(id,User.class);
    }


    public boolean amend(User user) {
        User user1 = null;
        if (user.getId()!=null){
            user1= this.findById(user.getId());
            if (user.getPassword()!=null)
            {
                user1.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
            }else if(user.getName()!=null){
                user1.setName(user.getName());
            }
            user1 = mongoTemplate.save(user1);
        }else
        {
            user1 = mongoTemplate.save(user);
        }
        return user1!=null?true:false;
    }

    public User findByUserName(String username)
    {
        Query query = new Query();
        query.addCriteria(Criteria.where("username").is(username));
        User user = mongoTemplate.findOne(query, User.class);
        return user;
    }

}
